package cn.itcast.gateway.filters;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;

@Component
public class PaiziFilter extends ZuulFilter {
    /**
     * 过滤器的类型
     *
     *
     * pre--->routing ---->post
     *
     * routing--->post
     *
     * pre---->error--->post
     *
     * pre---->routing---->error---->post
     *
     * pre--->routing---->post---->error
     *
     *
     * @return
     */
    @Override
    public String filterType() {
        return "pre";
    }


    /**
     * load-on-startup  >=1
     *
     * @return
     */

    @Override
    public int filterOrder() {
        return 1;
    }

    /**
     *
     * true 表示过滤器生效
     * false 表示过滤器不生效
     *
     * @return
     */
    @Override
    public boolean shouldFilter() {
        return true;
    }


    /**
     * 过滤执行的过程
     *
     * 如果是拦截了，要声明处理
     *
     * 如果是放行了，则不用理会
     *
     * @return
     * @throws ZuulException
     */
    @Override
    public Object run() throws ZuulException {

        //获取当前的上下文
        RequestContext currentContext = RequestContext.getCurrentContext();

        //获取当前请求的对象
        HttpServletRequest request = currentContext.getRequest();


        //获取请求参数
        String paizi = request.getParameter("paizi");

        //判断如果为空，实现拦截（不响应）
        if (StringUtils.isEmpty(paizi)){
            //确定不响应
            currentContext.setSendZuulResponse(false);
            currentContext.setResponseStatusCode(401);
        }

        return null;
    }
}
